<template>
  <div class="addFrom">
    <header>
      <span></span>基本信息
    </header>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="ruleForm.projectName" placeholder="请输入项目名称" clearable :maxlength="40"></el-input>
      </el-form-item>
      <el-form-item label="项目类型" prop="projectType">
        <el-select v-model="ruleForm.projectType" placeholder="请选择项目类型" clearable>
          <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.name"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目造价(万元)">
        <el-input v-model="ruleForm.projectCost" type="number" placeholder="请输入项目造价" clearable></el-input>
      </el-form-item>
      <el-form-item label="建筑面积(m²)">
        <el-input v-model="ruleForm.projectAera" type="number" placeholder="请输入建筑面积"  clearable></el-input>
      </el-form-item>
      <el-form-item label="计划开工时间">
        <el-date-picker
          v-model="ruleForm.planDate"
          type="date"
          placeholder="请选择计划开工时间"
          value-format="yyyy-MM-dd HH:mm:ss"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="计划竣工时间">
        <el-date-picker
          v-model="ruleForm.planFinDate"
          type="date"
          placeholder="请选择计划竣工时间"
          value-format="yyyy-MM-dd HH:mm:ss"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="项目负责人">
        <el-input v-model="ruleForm.projectMananger" placeholder="请输入项目负责人" maxlength="10" clearable></el-input>
      </el-form-item>
      <el-form-item label="负责人手机号">
        <el-input v-model="ruleForm.phone" placeholder="请输入负责人手机号" clearable></el-input>
      </el-form-item>
      <el-form-item label="项目状态" prop="projectCompletion">
        <el-select v-model="ruleForm.projectCompletion" placeholder="请选择项目状态" clearable>
          <el-option
            v-for="item in projectStatusList"
            :key="item.code"
            :label="item.label"
            :value="item.label"
          ></el-option>
        </el-select>
      </el-form-item>
      <br />
      <el-form-item label="项目图片" class="imgItem is-required">
        <el-upload
          :action="uploadImg"
          list-type="picture-card"
          :before-upload="beforeUpload"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :headers="headOfRequest"
          :with-credentials="true"
          :limit="4"
          :class="[ruleForm.imageList.length === 4 ? 'hide' : '']"
          :file-list="ruleForm.imageList"
          ref="elUpload"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <div class="error" v-if="imgError">请上传项目图片</div>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt />
        </el-dialog>
      </el-form-item>
      <el-form-item label="项目视频" class="uploadVideo">
            <div  class="videoList flex-start">
            <div class="videoItem flex-center" v-for="videoIt in uploadVideoList" :key="videoIt.uid">
            <video
                v-if="!videoIt.isShowProgress"
                :src="videoIt.url"
                width="100%"
                height="100%"
                controls
              ></video>
              <el-progress
                v-else
                type="circle"
                :percentage="videoIt.percentage"
                :show-text="isShowText"
                :stroke-width="stroke_width"
                :color="circleColor"
              ></el-progress>
              <div class="deleteVideo cp" @click="deleteVideo(videoIt.uid)">删除</div>
            </div>
          </div>
          <el-upload
            class="avatar-uploader"
            :action="uploadVideo"
            ref="elUpload"
            list-type="picture-card"
            :before-upload="beforeUpload_vdo"
            :on-success="onsuccessUpload_vdo"
            :on-progress="on_progress"
            :with-credentials="true"
            :headers="headOfRequest"
            :class="[uploadVideoList.length === 4 ? 'hide' : '']"
            :show-file-list="false"
          >
            <div class="nopic flex-column">
              <img
                src="@/assets/file/addPic.png"
                alt
                width="48px"
              />
              <div
                class="addpics"
              >
                添加视频
              </div>
            </div>
            <span class="pictips">*视频文件大小小于500M</span>
          </el-upload>
        </el-form-item>
      <br />
      <el-form-item label="项目简介">
        <el-input
          type="textarea"
          placeholder="请输入项目简介"
          resize="none"
          :rows="8"
          :maxlength="100"
          v-model="ruleForm.projectInfo"
        ></el-input>
        <p class="maxLength">{{ maxLength }} / 100</p>
      </el-form-item>
      <br />
      <el-form-item label="项目所在地" prop="projectThumAd">
        <el-select
          placeholder="省"
          clearable
          class="province"
          v-model="province"
          @change="selectProvince"
        >
          <el-option
            v-for="item in provinceList"
            :label="item.name"
            :key="item.code "
            :value="item.code"
          ></el-option>
        </el-select>
        <el-select placeholder="市" clearable class="city" v-model="city" @change="selectCity">
          <el-option
            v-for="item in cityList"
            :label="item.name"
            :key="item.code"
            :value="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="详情地址" prop="projectAd">
        <el-input type="text" v-model="ruleForm.projectAd" clearable placeholder="请输入详情地址" maxlength="40"></el-input>
      </el-form-item>
      <el-form-item label="经度">
        <el-input type="text" placeholder="请输入经度" class="longitude" v-model="center.lng" disabled></el-input>
      </el-form-item>
      <br>
      <el-form-item label="纬度">
        <el-input type="text" placeholder="请输入纬度" class="latitude" v-model="center.lat" disabled></el-input>
        <br />
        <baidu-map
          v-if="showMap"
          class="bm-view"
          ak="jQRGy1L64Ojjdmrti7xUxZzLqNDaHCOO"
          :center="addCenter"
          :zoom="map.zoom"
          @moving="syncCenterAndZoom"
          @moveend="syncCenterAndZoom"
          @zoomend="syncCenterAndZoom"
          :keyboard="false"
          :mapClick="false"
        >
          <bm-marker :dragging="false" :position="center"></bm-marker>
          <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
        </baidu-map>
      </el-form-item>
      <div class="componyInfo">
        <span></span>公司信息
      </div>
      <el-form-item label="施工单位" prop="consUnit">
        <el-input v-model="ruleForm.consUnit" type="text" placeholder="请输入施工单位" maxlength="30" clearable></el-input>
      </el-form-item>
      <el-form-item label="建设单位">
        <el-input v-model="ruleForm.devpUnit" type="text" placeholder="请输入建设单位"  maxlength="30" clearable></el-input>
      </el-form-item>
      <el-form-item label="监管单位">
        <el-input v-model="ruleForm.versionUnit" type="text" placeholder="请输入监管单位"  maxlength="30" clearable></el-input>
      </el-form-item>
      <el-form-item label="设计单位">
        <el-input v-model="ruleForm.designUnit" type="text" placeholder="请输入设计单位"  maxlength="30" clearable></el-input>
      </el-form-item>
      <el-form-item label="勘察单位">
        <el-input v-model="ruleForm.surveyUnit" type="text" placeholder="请输入勘察单位"  maxlength="30" clearable></el-input>
      </el-form-item>
      <br />
      <el-form-item class="test">
        <span class="create" @click="addProject('ruleForm')">创建</span>
        <span class="warning" v-if="isShowWarning">您有必填项未填，请完成填写后再点击“创建”按钮。</span>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { uploadImg, uploadVideo } from '@/api/file'
import { addProject } from '../../../api/project'
import { getToken } from '../../../utils/token'
import { validTelephone } from '../../../utils/validate'
import provinceList from '../../../json/provinces.json'
import cityList from '../../../json/cities.json'
import baiduMap from '../../../../node_modules/vue-baidu-map/components/map/Map'
import bmMarker from '../../../../node_modules/vue-baidu-map/components/overlays/Marker'
import bmNavigation from '../../../../node_modules/vue-baidu-map/components/controls/Navigation'

export default {
  name: 'addForm',
  data () {
    const validPhone = (rule, value, callback) => {
      if (validTelephone(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的手机号格式'))
      }
    }
    return {
      imgError: false,
      isShowText: false,
      stroke_width: 10,
      circleColor: '#75FF6D',
      percentage: 0,
      uploadVideo: uploadVideo,
      videoUrl: '',
      isShowWarning: false,
      uploadVideoList: [], // 上传视频列表
      // 上传图片的url地址
      uploadImg: uploadImg,
      // 上传图片组件的请求头设置
      headOfRequest: { token: getToken() },
      // 上传图片组件查看大图的设置
      dialogImageUrl: '',
      dialogVisible: false,
      // 项目类型下拉菜单
      typeList: [
        { id: 0, name: '房屋建筑工程' },
        { id: 1, name: '市政工程' },
        { id: 2, name: '工业建筑工程' },
        { id: 3, name: '轨道交通工程' },
        { id: 4, name: '水利工程' },
        { id: 5, name: '电力工程' }
      ],
      // 项目状态设置
      projectStatusList: [
        { label: '监测中', code: 0 },
        { label: '未监测', code: 1 },
        { label: '监测完成', code: 2 }
      ],
      // 省级区划列表
      provinceList,
      // 选中的省级区划
      province: '',
      // 市级区划列表
      cityList: [],
      // 选中的市级区划
      city: '',
      // map
      map: {
        // 缩放比例
        zoom: +''
      },
      center: {
        lng: '',
        lat: ''
      },
      showMap: true,
      ruleForm: {
        projectName: '',
        projectType: '',
        projectCost: '',
        projectAera: '',
        planDate: '',
        planFinDate: '',
        projectMananger: '',
        projectCompletion: '',
        imageList: [],
        projectInfo: '',
        province: '',
        projectAd: '',
        projectThumAd: '',
        projectMap: '',
        phone: '',
        consUnit: '',
        devpUnit: '',
        versionUnit: '',
        designUnit: '',
        surveyUnit: ''
      },
      rules: {
        projectName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' }
        ],
        projectType: [
          { required: true, message: '请选择项目类型', trigger: 'change' }
        ],
        projectCompletion: [
          { required: true, message: '请选择项目状态', trigger: 'change' }
        ],
        imageList: [{ required: true, message: '' }],
        projectThumAd: [{ required: true, message: '请选择项目所在地', trigger: 'blur' }],
        projectAd: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
        consUnit: [
          { required: true, message: '请输入施工单位名称', trigger: 'blur' }
        ],
        phone: [{ required: true, validator: validPhone, trigger: 'change' }]
      }
    }
  },
  computed: {
    // ruleForm () {
    //   return this.$store.state.projectManage.projectInfo
    // },
    // imgInput () {
    //   return this.ruleForm.figure.join()
    // },
    maxLength () {
      return this.ruleForm.projectInfo.length
    },
    addCenter () {
      return this.ruleForm.projectThumAd || '北京'
    }
  },
  components: {
    baiduMap,
    bmMarker,
    bmNavigation
  },
  methods: {
    // 图片上传之前的钩子
    beforeUpload (file) {
      const testmsg = /^image\/(jpg|JPG|jpeg|png|PNG|bmp|BMP)$/.test(file.type)
      const isLT3M = file.size / 1024 / 1024 <= 3
      if (!testmsg) {
        this.$message.error('图片格式错误')
        return false
      }
      if (!isLT3M) {
        this.$message.error('上传图片大小不能超过3M!')
        return false
      }
      return testmsg && isLT3M
    },
    // 图片上传成功的钩子
    handleSuccess (res, file, fileList) {
      // console.log(fileList)
      // const arr = this.$refs.elUpload.$children[1].$el.classList
      // arr.add('hidden')
      this.ruleForm.imageList = fileList
      this.imgError = false
    },
    // 图片移除成功的钩子
    handleRemove (file, fileList) {
      // const arr = this.$refs.elUpload.$children[1].$el.classList
      // arr.remove('hidden')
      this.ruleForm.imageList = this.ruleForm.imageList.filter(item => item.uid !== file.uid)
      this.imgError = !this.ruleForm.imageList.length
      // deleteImg(11, file.response.data.url)
    },
    // 查看大图的钩子
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 省级区划发生改变的函数
    selectProvince (val) {
      this.cityList = cityList.filter(item => item.provinceCode === val)
      // console.log(this.cityList)
      if (val) {
        this.ruleForm.province = this.provinceList.filter(
          item => item.code === val
        )[0].name
      } else {
        this.ruleForm.province = ''
        this.ruleForm.projectThumAd = ''
      }
      // console.log(this.ruleForm)
      this.city = ''
    },
    // 市级区划发生改变的函数
    selectCity (val) {
      this.ruleForm.projectThumAd = this.city
    },
    // 获取当前经纬度
    syncCenterAndZoom (e) {
      const { lng, lat } = e.target.getCenter()
      this.center.lng = lng
      this.center.lat = lat
      this.ruleForm.projectMap = 'lng:' + lng + ', lat:' + lat
      this.zoom = e.target.getZoom()
    },
    // 新增项目
    addProject (formName) {
      this.$refs[formName].validate(valid => {
        this.imgError = !this.ruleForm.imageList.length
        if (valid && !this.imgError) {
          this.isShowWarning = false
          // console.log('this.ruleForm', this.ruleForm)
          this.ruleForm.figures = this.ruleForm.imageList.map(item => item.response.data.id)
          this.ruleForm.videoIds = this.uploadVideoList.map(item => item.id)
          addProject(this.ruleForm).then(res => {
            if (res.data.code === 200) {
              this.$message({
                message: res.data.message,
                type: 'success',
                duration: 1000
              })
              this.$router.push('projectMain')
            }
          })
        } else {
          this.isShowWarning = true
        }
      })
    },
    // 视频上传
    beforeUpload_vdo (file) {
      const testmsg = /^video\/(mp4|avi|rmvb|ts|flv|wmv|m2v|mkv)$/.test(
        file.type
      )
      const isLT3M = file.size / 1024 / 1024 <= 300
      if (!testmsg) {
        this.$message.error('视频格式错误')
        return false
      }
      if (!isLT3M) {
        this.$message.error('上传视频大小不能超过300M!')
        return false
      }
      this.uploadVideoList.push({ uid: file.uid, percentage: 0, url: null, isShowProgress: true })
      return testmsg && isLT3M
    },
    onsuccessUpload_vdo (res, file) {
      this.uploadVideoList.forEach(item => {
        if (item.uid === file.uid) {
          item.url = file.url
          item.id = file.response.data.id
          item.isShowProgress = false
        }
      })
    },
    deleteVideo (uid) {
      this.uploadVideoList = this.uploadVideoList.filter(item => item.uid !== uid)
    },
    on_progress (event, file, fileList) {
      this.uploadVideoList.forEach(item => {
        if (item.uid === file.uid) {
          item.percentage = event.percent
        }
      })
    }
  }
  // created () {
  //   if (getProjectId()) {
  //     this.$store.dispatch('projectManage/getProjectInfo')
  //   }
  // }
}
</script>

<style lang="scss" scoped>

::v-deep .el-form-item__label {
  width: 168px !important;
  text-align: right;
}
::v-deep .el-form-item__content {
  float: left;
}
::v-deep .el-form-item.test {
  position: relative;
  height: 23px;
  .warning{
    width: 500px;;
    position: absolute;
    top: 30px;
    left: 400px;
    height: 17px;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #FF2B2B;
    line-height: 17px;
  }
}
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
::v-deep .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
::v-deep .anchorBL {
  display: none;
}

::v-deep .hidden {
  display: none !important;
}

.addFrom {
  width: 100%;
  background-color: #fff;
  margin-top: 23px;
  padding-bottom: 30px;
  border-radius: 5px;
  header {
    height: 85px;
    line-height: 85px;
    font-size: 18px;
    padding-left: 30px;
    font-weight: 500;
    span {
      border-left: 4px solid #4868ff;
      margin-right: 10px;
    }
  }
  .el-form {
    padding-left: 122px;

    .el-input {
      width: 400px;
    }

    .el-select {
      width: 400px;
    }

    .componyInfo {
      height: 85px;
      line-height: 85px;
      font-size: 18px;
      padding-left: 30px;
      font-weight: 500;
      margin-left: -120px;
      span {
        border-left: 4px solid #4868ff;
        margin-right: 10px;
      }
    }

    .el-form-item {
      display: inline-block;
      position: relative;
      &:nth-of-type(odd) {
        margin-right: 62px;
      }
      .el-textarea {
        width: 560px;
      }
      .maxLength {
        color: #c8c8c8;
        font-size: 14px;
        position: absolute;
        right: 16px;
        bottom: 0;
      }
      .province,
      .city,
      .area {
        width: 180px;
        margin-right: 10px;
      }

      .latitude {
        margin-bottom: 20px;
      }

      .bm-view {
        width: 560px;
        height: 300px;
      }

      .create {
        position: absolute;
        height: 48px;
        width: 172px;
        background-color: #4868ff;
        text-align: center;
        line-height: 48px;
        border-radius: 24px;
        color: #fff;
        font-size: 18px;
        cursor: pointer;
        left: 170px;
      }
    }
  }
}
.uploadVideo{
      ::v-deep .el-form-item__content{
        display: flex;
        justify-content: flex-start;
        .videoList{
          .videoItem{
            position: relative;
            width: 284px;
            height: 172px;
            margin-right: 20px;
           .el-progress-circle {
              width: 40px !important;
              height: 40px !important;
            }
            .deleteVideo{
              display: none;
              position: absolute;
              width: 100%;
              height: 36px;
              bottom: 0;
              left: 0;
              line-height: 36px;
              text-align: center;
              background: rgba(0,0,0,0.50);
              color: #fff;
            }
            &:hover{
              .deleteVideo{
                display: block;
              }
            }
          }
        }
      }
}
  ::v-deep .avatar-uploader{

  .el-upload--picture-card {
    width: 284px;
    height: 172px;
    background-color: #fff;
    .nopic {
      height: 100%;
      align-items: center;
      justify-content: center;
      position: relative;
      .addpics {
        line-height: 20px;
        height: 20px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(200, 200, 200, 1);
      }
    }
    .pictips {
      line-height: 20px;
      position: absolute;
      top: 0;
      left: 721px;
      height: 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(255, 180, 21, 1);
      cursor: default;
    }

  }
    }

  .hide ::v-deep .el-upload--picture-card{
    display: none;
  }
  ::v-deep .imgItem.el-form-item{
    display: block !important;
  }
  .error{
    position: absolute;
    bottom: -15px;
    line-height: 12px;
    font-size: 12px;
    color: #F56C6C;
  }
</style>
